package com.javatian.controller;

import com.github.pagehelper.PageInfo;
import com.javatian.common.Result;
import com.javatian.entity.Account;
import com.javatian.entity.CartInfo;
import com.javatian.entity.GoodsInfo;
import com.javatian.entity.OrderInfo;
import com.javatian.service.CartInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 购物车信息控制器
 */
@RestController
@RequestMapping(value = "/cartInfo")
public class CartInfoController {

    //用户信息
    @Value("${const.user}")
    private String user;

    @Resource
    private CartInfoService cartInfoService;


    /**
     * 新增一个购物车信息
     */
    @PostMapping
    public Result<CartInfo> add(@RequestBody CartInfo cartInfo){
        return Result.success( cartInfoService.add(cartInfo));
    }

    /**
     * 根据主键id删除一个购物车信息
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id){
        cartInfoService.delete(id);
        return Result.success();
    }

    /**
     * 修改一个购物车信息
     */
    @PutMapping
    public Result update(@RequestBody CartInfo cartInfo){
        cartInfoService.update(cartInfo);
        return Result.success();
    }

    /**
     * 根据主键id获取一个购物车信息对象
     */
    @GetMapping("/{id}")
    public Result<CartInfo> detail(@PathVariable Long id){
        CartInfo cartInfo = cartInfoService.findById(id);
        return Result.success(cartInfo);
    }

    /**
     * 查询某个用户所有购物车信息记录
     */
    @GetMapping
    public Result<List<GoodsInfo>> all(@RequestParam ("userId")Long userId, @RequestParam("level")Integer level){
        return Result.success(cartInfoService.findAll(userId,level));
    }

    /**
     * 根据条件分页查询
     * @param pageNum 第几页
     * @param pageSize 每页数量
     * @return 当前页的List列表
     */
    @GetMapping("/page")
    public Result<PageInfo<CartInfo>> page(@RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                            @RequestParam(required = false,defaultValue = "5") Integer pageSize,
                                            HttpServletRequest request){
        Account account =(Account) request.getSession().getAttribute(user);
        return Result.success(cartInfoService.findPage(pageNum,pageSize,account));
    }

    /**
     * 删除某用户购物车里的某个商品
     */
    @DeleteMapping("/goods/{userId}/{level}/{goodsId}")
    public Result deleteGoods(@PathVariable Long userId,@PathVariable Integer level,@PathVariable Long goodsId){
        cartInfoService.deleteGoods(userId,level,goodsId);
        return Result.success();
    }
}
